const regeneratorRuntime = require("../../utils/runtime.js")
const {
  _post,
  _get,
  _request
} = require('../../utils/request.js')
let debounceCB
let debounce = (fn, delay) => {
  let timer = null // 借助闭包
  return () => {
    if (timer) {
      clearTimeout(timer)
      debounceCB = null
    }
    timer = setTimeout(fn, delay) // 简化写法
    debounceCB = timer
  }
}

const login = require('../../utils/utils.js')


Page({
  data: {
    pickerShow: false,
    articleId: 0,
    article: {},
    articleHeight: 0,
    pageHeight: 1,
    readingProcess: 0,
    isCollected: false,
    loginRes: false,
    readTime: 1,

    popupShow: true,
    tale: [],
    taleColumn: [],
    currentTale: 0,

    scroll2Tale: '',
    scrollTop: 0

  },

  async onLoad(e) {
    if (e.id) {
      this.setData({
        articleId: e.id,
      })

      await this.getArticle()
    }
  },


  async refreshCollected() {
    let collected = await _get(`/collection/${this.data.articleId}`, {})
    this.setData({
      isCollected: collected.data
    })
  },

  onUnload() {
    if (debounceCB) {
      clearTimeout(debounceCB)
    }
  },

  saveHistory() {
    let article = this.data.article
    article['add_time'] = new Date().valueOf()
    let history = JSON.parse(wx.getStorageSync('history') || '{}')
    history[article['id'] + ''] = article
    wx.setStorageSync('history', JSON.stringify(history))
  },

  async getArticle() {
    let res = await _get(`/article/${this.data.articleId}`, {})
    if (res.code === 0) {
      this.setData({
        article: res.data,
        token: wx.getStorageSync('auth')
      })

      // 存储历史浏览记录

      this.saveHistory()

      if (this.data.token) {
        await this.refreshCollected()
      }

      this.calcWordNum(res.data.content || '')
    }

    let that = this
    setTimeout(() => {
      let query = wx.createSelectorQuery()
      query.select('#article').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function(res) {
        if (res[0] && res[0]['height']) {
          that.setData({
            articleHeight: res[0]['height']
          })
        }
      })

      query.select('page').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function(res) {
        if (res[1] && res[1]['scrollHeight']) {
          that.setData({
            pageHeight: res[1]['scrollHeight']
          })
        }
      })

    }, 800)
  },

  calcWordNum(words = '') {
    const ch = /[\u4e00-\u9fa5]/g,
      en = /[a-zA-Z]/g
    let total = words.match(ch).length + words.match(en).length
    console.log(total)
    let times = Math.ceil(total / 350)
    if (!times > 0) {
      times = 1
    }
    this.setData({
      readTime: times
    })
  },

  handleScroll(e) {
    let that = this
    let d = debounce(() => {
      let query = wx.createSelectorQuery()
      query.select('#article').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec(function(res) {
        if (res && res[0] && res[0].bottom) {
          let data = res[0]
          let calc = parseInt((100 -
            (data.bottom - that.data.pageHeight) / ((that.data.articleHeight - that.data.pageHeight) / 100)))
          let nowProcess = calc < 0 ? 0 : calc
          let popupShow = nowProcess === 0 || nowProcess >= 100
          that.setData({
            readingProcess: nowProcess,
            popupShow
          })
        }
      })
    }, 500)
    d()
  },

  handlePopupOnClose() {
    this.setData({
      popupShow: false
    })
  },

  handleGoHome() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  onShareAppMessage() {
    let shareInfo = {
      title: this.data.article.title || '推荐给你一篇好文章～',
      imageUrl: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1579524369513&di=495f486dd0f5a9ac99fe090b49ac68f4&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201803%2F03%2F20180303170608_nJAx8.jpeg',
      path: this.data.articleId ? 'pages/article/article?id=' + this.data.articleId : 'pages/index/index',
      success() {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log('转发成功')
        }
      },
      fail() {
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log('取消转发')
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log('转发失败')
        }
      },
    }

    return shareInfo
  },

  handleGetTale(e) {
    if (e.detail.tale) {
      this.setData({
        tale: e.detail.tale,
        taleColumn: e.detail.tale.map(item => item.content)
      })
    }
  },

  handleJump(e) {
    this.setData({
      scrollTop: e.detail.top
    })
  },


  async handleAddCollection() {
    let res
    if (!this.data.isCollected) {
      res = await _post('/collection', {
        cid: this.data.articleId * 1
      })
    } else {
      res = await _request('/collection', 'DELETE', {
        cid: this.data.articleId * 1
      })
    }
    if (res.code === 0) {
      await this.refreshCollected()
    }
  },

  handleSearchTag(e) {
    wx.navigateTo({
      url: '/pages/category/category?label=' + e.currentTarget.dataset.name,
    })
  },

  handleShowPicker() {
    this.setData({
      pickerShow: true
    })
  },

  handlePickerChange(e) {},

  handlePickerCancel() {
    this.setData({
      pickerShow: false
    })
  },

  handlePickerConfirm(e) {
    const {
      picker,
      value,
      index
    } = e.detail
    this.setData({
      currentTale: index,
      pickerShow: false,
      scroll2Tale: this.data.tale[index]['tale']
    })
  },
})